package com.netease.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.netease.domain.Commodity;
import com.netease.domain.ShoppingCart;
import com.netease.domain.User;
import com.netease.service.CommodityService;
import com.netease.service.ShoppingcartService;

/**
 * Servlet implementation class Ajax
 */
@WebServlet("/addtoshoppingcart")
public class AddToShoppingCartServlet extends HttpServlet {

	@Autowired
	private ShoppingcartService shoppingcartService;

	@Autowired
	private CommodityService commodityService;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddToShoppingCartServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String id = request.getParameter("id");
		int amount = Integer.parseInt(request.getParameter("amount"));
		User user = (User) request.getSession().getAttribute("sys_user_key");
		Commodity c = commodityService.findOne(id);
		PrintWriter out = response.getWriter();

		List<ShoppingCart> scs = shoppingcartService.findAllByUserId(user.getId());
		ShoppingCart sc = null;
		for (ShoppingCart s:scs)
		{
			if (s.getCommodityId().equals(id))
			{
				sc = s;
				break;
			}
		}
		
		boolean flag = true;//true表示之前购物车里没有该商品
		if (sc != null)
		{
			amount = sc.getAmount()+amount;
			sc.setAmount(amount);
			flag = false;
			
		}
		else
		{
			sc = new ShoppingCart(c);
			sc.setAmount(amount);
			sc.setUser(user);
			
		}
		if (amount <= c.getRemainningAmount()) {
			try {
				
				if (flag)
				{
					shoppingcartService.save(sc);
				}
				else
				{
					shoppingcartService.update(sc);
				}
				out.print("true");
			} catch (Exception e) {
				// TODO: handle exception
				out.print("false");
			}
		} else {
			out.print("库存不足");
		}
		
		out.close();

	}

}
